package com.zdkj.subway.check.service;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.check.entity.SwAuTvmSingleAssist;
import com.zdkj.subway.check.entity.SwParamLine;
import com.zdkj.subway.check.entity.SwParamStation;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.SwAuTvmSingleAssistMapper;
import com.zdkj.subway.check.mapper.SwParamLineMapper;
import com.zdkj.subway.check.mapper.SwParamStationMapper;
import com.zdkj.subway.check.mapper.SysUserMapper;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.util.DateFormat;
import com.zdkj.subway.check.util.LocalDateConverter;
import com.zdkj.subway.check.util.LocalDateTimeConverter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
/**
 * 数据协查管理-TVM系统差异协查-TVM单台设备差异
 * TVM票款差异协查-单台设备 SW_AU_TVM_SINGLE_ASSIST
 */
@Service
@Slf4j
public class SwAuTvmSingleAssistService {

    //使用指定类初始化日志对象
    private static final Logger LOGGER = LoggerFactory.getLogger(SwAuTvmSingleAssist.class);
    @Resource
    private SwAuTvmSingleAssistMapper swAuTvmSingleAssistMapper;
    @Resource
    private SwParamLineMapper swParamLineMapper;
    @Resource
    private SwParamStationMapper swParamStationMapper;
    @Resource
    private SwAuTvmSingleAssistToService swAuTvmSingleAssistToService;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * 导入
     * @param file
     * @return
     * @throws Exception
     */
    public boolean importTvmSingle(final File file) throws Exception {
        List<Map<Integer, String>> listMap = EasyExcelFactory.read(file).sheet().headRowNumber(2).doReadSync();
        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwAuTvmSingleAssist> tvmCashList = new ArrayList<>();
            MultipartFileToFile.delteTempFile(file);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 key表示所在的列位置 value表示所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                SwAuTvmSingleAssist tvmSing = new SwAuTvmSingleAssist();
                //主键id
                tvmSing.setId(Integer.parseInt(data.get(0)));
                //SC售票金额
                tvmSing.setSaleAmount(getData(data.get(5)));
                //SC充值金额
                tvmSing.setDepositAmount(getData(data.get(6)));
                //SC故障退款金额
                tvmSing.setErrorRefundAmount(getData(data.get(7)));
                //系统金额
                tvmSing.setTvmBillOrderMoney(getData(data.get(8)));
                //实点金额
                tvmSing.setActualMoney(getData(data.get(9)));
                //差异金额（元）
                tvmSing.setDiffMoney(getData(data.get(10)));
                //回馈售卖金额
                tvmSing.setReplySaleMoney(getData(data.get(11)));
                //回馈充值金额
                tvmSing.setReplyRechargeMoney(getData(data.get(12)));
                //回馈故障退款金额
                tvmSing.setReplyErrorReturnMoney(getData(data.get(13)));
                //合计
                tvmSing.setReplyTotal(getData(data.get(14)));
                if ("系统原因".equals(data.get(15))) {
                    //回馈原因
                    tvmSing.setReplyReason("1");
                } else {
                    //回馈原因
                    tvmSing.setReplyReason("2");
                }
                //回馈描述
                tvmSing.setReplyContent(data.get(16));
                //已回馈
                tvmSing.setReplyStatus("1");
                tvmCashList.add(tvmSing);
            }
            //  增加根据id批量更新回馈信息方法
            if (CollectionUtils.isNotEmpty(tvmCashList)) {
                swAuTvmSingleAssistToService.updateBatchById(tvmCashList);
            }
        }
        return true;
    }
    private BigDecimal getData(String money){
        try {
            BigDecimal num = new BigDecimal("100");
            BigDecimal itemMoney = new BigDecimal(money).setScale(2, BigDecimal.ROUND_HALF_UP);
            itemMoney = itemMoney.multiply(num);
            return itemMoney;
        } catch (Exception e) {
            return new  BigDecimal("0.00");
        }

    }
    /**
     * 导出
     * @param
     * @return
     */
    public void export(String ids, String tag, SwAuTvmSingleAssist params, HttpServletResponse response) throws ParseException {
        //线路、站点、支付方式中文名 根据未回馈的查询 差异类型 compare_type = 4 and assist_status =2
        List<SwAuTvmSingleAssist> records = new ArrayList<>();
        if(ids == null || ids.isEmpty()) {
            Map<String,String> param = new HashMap<>();
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getLineCode())){
                param.put("lineCode",params.getLineCode());
            }else {
                if(StringUtils.isEmpty(params.getLineCode())) {
                    List<String> lineCodeList = new ArrayList<>();
                    PigxUser user = SecurityUtils.getUser();
                    Map<String, Object> p1 = new HashMap<>();
                    p1.put("user_code", user.getUserCode());
                    List<SysUser> sysUsers = sysUserMapper.selectByMap(p1);
                    SysUser sysUser = sysUsers.get(0);
                    String managementLineStation = sysUser.getManagementLineStation();
                    if (!StringUtils.isEmpty(managementLineStation)) {
                        JSONArray managementLineStations = JSONArray.parseArray(managementLineStation);
                        for (int i = 0; i < managementLineStations.size(); i++) {
                            JSONObject jsonObject1 = managementLineStations.getJSONObject(i);
                            //存在多条线路
                            lineCodeList.add(jsonObject1.getString("line"));
                        }
                        param.put("lineCode", org.apache.commons.lang3.StringUtils.join(lineCodeList,","));
                    }else {
                        //不管辖线路
                        param.put("lineCode", sysUser.getLineCode());
                    }
                }
            }
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getStationCode())){
                param.put("stationCode",params.getStationCode());
            }
            if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotEmpty(params.getTvmCode())){
                param.put("tvmCode",params.getTvmCode());
            }
            if(params.getIncomeTime()!=null){
                param.put("incomeTime", DateFormat.date_ex_str(params.getIncomeTime()));
            }
            param.put("assistInvestStatus", params.getAssistInvestStatus());
            param.put("kyAssistInvestStatus", params.getKyAssistInvestStatus());
            List<Map<String, Object>> swAuTvmTvmSingleAssistList = swAuTvmSingleAssistMapper.getSwAuTvmSingleAssistLists(param);
            records = getMapList(swAuTvmTvmSingleAssistList);
        }else {
            Map<String,String> param = new HashMap<>();
            param.put("ids",ids);
            List<Map<String, Object>> swAuTvmTvmSingleAssistList = swAuTvmSingleAssistMapper.getSwAuTvmSingleAssistLists(param);
            records = getMapList(swAuTvmTvmSingleAssistList);

        }
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = null;
            WriteSheet writeSheet = null;
            if("keyun".equals(tag)){
                fileName = URLEncoder.encode("TVM单台设备客运协查", "UTF-8");
                excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/export/SwAuKeYunTvmSingleAssistToExcelTemplate.xlsx");
                writeSheet = EasyExcel.writerSheet("TVM单台设备客运协查").build();
            }else {
                fileName = URLEncoder.encode("TVM单台设备机电协查", "UTF-8");
                excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/export/SwAuTvmSingleAssistToExcelTemplate.xlsx");
                writeSheet = EasyExcel.writerSheet("TVM单台设备机电协查").build();
            }
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                    .registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter())
                    .withTemplate(excelTemplateIs).build();
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            //直接写入Excel数据(list是我查询并需导出的数据，并且里面的字段和excel需要导出的字段对应)
            excelWriter.fill(records, fillConfig, writeSheet);
            excelWriter.finish();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("TVM单台设备协查导出失败!");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }

    private List<SwAuTvmSingleAssist> getMapList(List<Map<String, Object>> res) {
        List<SwAuTvmSingleAssist> records = new ArrayList<>();
        for (int i = 0; i < res.size(); i++) {
            Map<String, Object> map = res.get(i);
            SwAuTvmSingleAssist swAuTvmSingleAssist = new SwAuTvmSingleAssist();
            swAuTvmSingleAssist.setId((Integer) map.get("id"));
            SwParamLine swParamLine = swParamLineMapper.selectOne(Wrappers.<SwParamLine>lambdaQuery().eq(SwParamLine::getCode, map.get("lineCode")));
            SwParamStation swParamStation = swParamStationMapper.selectOne(Wrappers.<SwParamStation>lambdaQuery()
                    .eq(SwParamStation::getLineCode,map.get("lineCode")).eq(SwParamStation::getCode, map.get("stationCode")));
            swAuTvmSingleAssist.setLineCode(swParamLine.getName());
            swAuTvmSingleAssist.setStationCode(swParamStation.getName());
            swAuTvmSingleAssist.setTvmCode((String) map.get("tvmCode"));
            swAuTvmSingleAssist.setIncomeDate(DateFormat.StringTurnLocalDate(map.get("incomeTime").toString()));
            swAuTvmSingleAssist.setSaleAmount(getFixed(map.get("saleAmount")));
            swAuTvmSingleAssist.setDepositAmount(getFixed(map.get("depositAmount")));
            swAuTvmSingleAssist.setErrorRefundAmount(getFixed(map.get("errorRefundAmount")));
            swAuTvmSingleAssist.setTvmBillOrderMoney(getFixed(map.get("tvmBillOrderMoney")));
            swAuTvmSingleAssist.setActualMoney(getFixed(map.get("actualMoney")));
            swAuTvmSingleAssist.setDiffMoney(getFixed(map.get("diffMoney")));
            swAuTvmSingleAssist.setReplyDiffMoney(getFixed(map.get("replyDiffMoney")));
            swAuTvmSingleAssist.setReplySaleMoney(getFixed(map.get("replySaleMoney")));
            swAuTvmSingleAssist.setReplyRechargeMoney(getFixed(map.get("replyRechargeMoney")));
            swAuTvmSingleAssist.setReplyErrorReturnMoney(getFixed(map.get("replyErrorReturnMoney")));
            swAuTvmSingleAssist.setReplyTotal(swAuTvmSingleAssist.getReplySaleMoney().add(swAuTvmSingleAssist.getReplyRechargeMoney()).add(swAuTvmSingleAssist.getReplyErrorReturnMoney()));
            swAuTvmSingleAssist.setReplyContent((String) map.get("replyContent"));
            swAuTvmSingleAssist.setKyReplyDetail((String) map.get("kyReplyDetail"));
            swAuTvmSingleAssist.setOperatorId((Integer) map.get("operatorId"));
            swAuTvmSingleAssist.setOperatorCode((String) map.get("operatorCode"));//机电回馈人工号
            swAuTvmSingleAssist.setOperatorName((String) map.get("operatorName"));//机电回馈人
            swAuTvmSingleAssist.setKyReplyCode((String) map.get("kyReplyCode"));//客运回馈人工号
            swAuTvmSingleAssist.setKyReplyName((String) map.get("kyReplyName"));//客运回馈人
            swAuTvmSingleAssist.setReplyStatus(StringUtils.isEmpty(String.valueOf(map.get("replyStatus"))) ? "未回馈" : ("0".equals(String.valueOf(map.get("replyStatus"))) ? "未回馈" : "已回馈"));
            swAuTvmSingleAssist.setReplyReason(map.get("replyReason") ==null ? " " : (map.get("replyReason").equals("1") ? "系统原因" : "非系统原因"));
            swAuTvmSingleAssist.setKyReplyStatus(StringUtils.isEmpty(String.valueOf(map.get("kyReplyStatus"))) ? "未回馈" : ("0".equals(String.valueOf(map.get("kyReplyStatus"))) ? "未回馈" : "已回馈"));
            swAuTvmSingleAssist.setKyReplyReason(map.get("kyReplyReason") ==null ? " " : (map.get("kyReplyReason").equals("1") ? "系统原因" : "非系统原因"));
            if(map.get("kyReplyDateTime")!=null){
                swAuTvmSingleAssist.setKyReplyDateTime(DateFormat.StringTurnLocalDateTime(map.get("kyReplyDateTime").toString()));
            }
            if(map.get("replyDateTime")!=null){
                swAuTvmSingleAssist.setJdReplyDateTime(DateFormat.StringTurnLocalDateTime(map.get("replyDateTime").toString()));
            }
            if(map.get("sendDateTime")!=null){
                swAuTvmSingleAssist.setSendDateTime(DateFormat.StringTurnLocalDateTime(map.get("sendDateTime").toString()));
            }
            records.add(swAuTvmSingleAssist);
        }
        return records;
    }
    private BigDecimal getFixed(Object money){
        try {
            BigDecimal num = new BigDecimal("100");
            BigDecimal moneyDecimal = new BigDecimal(String.valueOf(money));
            BigDecimal itemMoney = moneyDecimal.divide(num);
            return itemMoney;

        } catch (Exception e) {
            return new  BigDecimal("0.00");
        }

    }
    public Result getSwAuTvmSingleAssistList(JSONObject jsonObject) {
        //分页
        Integer startPage = jsonObject.getInteger("currentPage");
        Integer pageSize = jsonObject.getInteger("pageSize");

        //线路名称
        String lineCode = jsonObject.getString("lineCode");
        //tvm编号
        String tvmCode = jsonObject.getString("tvmCode");
        //站点名称
        String stationCode = jsonObject.getString("stationCode");
        //通知时间
        Date startTime = jsonObject.getDate("startTime");
        Date endTime = jsonObject.getDate("endTime");
        //回馈状态
        String replyStatus = jsonObject.getString("replyStatus");

        Example example = new Example(SwAuTvmSingleAssist.class);
        Example.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(lineCode)) {
            criteria.andEqualTo("lineCode", lineCode);
        }
        if (!StringUtils.isEmpty(tvmCode)) {
            criteria.andEqualTo("tvmCode", tvmCode);
        }
        if (!StringUtils.isEmpty(stationCode)) {
            criteria.andEqualTo("stationCode", stationCode);
        }
        if (!StringUtils.isEmpty(replyStatus)) {
            criteria.andEqualTo("replyStatus", replyStatus);
        }
        if (startTime != null && endTime != null) {
            criteria.andBetween("sendTime", startTime, endTime);
        }
        criteria.andEqualTo("assistInvestStatus", "2");
        PageHelper.startPage(startPage,pageSize);
        List<SwAuTvmSingleAssist> swAuTvmSingleAssists = swAuTvmSingleAssistMapper.selectByExample(example);

        PageInfo<SwAuTvmSingleAssist> swAuTvmSingleAssistPageInfo = new PageInfo<>(swAuTvmSingleAssists);

        JSONObject resultJson = new JSONObject();
        resultJson.put("list", swAuTvmSingleAssists);
        resultJson.put("pageInfo", swAuTvmSingleAssistPageInfo);
        return new Result(ResultDetailMsg.OK, resultJson);
    }

    /**
     * 车站票款差异通知 单独查询
     * @param jsonObject
     * @return
     */
    public Result getSwAuTvmSingleAssist(JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        SwAuTvmSingleAssist swAuTvmSingleAssist =
                swAuTvmSingleAssistMapper.selectByPrimaryKey(id);
        JSONObject resultJson = new JSONObject();
        resultJson.put("obj",swAuTvmSingleAssist);
        return new Result(ResultDetailMsg.OK,resultJson);
    }

    public Result updateSwAuTvmSingleAssist(JSONObject jsonObject) {
        SwAuTvmSingleAssist swAuTvmSingleAssist =
                JSONObject.parseObject(jsonObject.toJSONString(), SwAuTvmSingleAssist.class);
        int i = swAuTvmSingleAssistMapper.updateByPrimaryKeySelective(swAuTvmSingleAssist);
        return new Result(ResultDetailMsg.OK);
    }
}
